package edu.guet.server.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import edu.guet.server.model.User;
import edu.guet.server.service.UserService;
import edu.guet.server.utils.JWTUtils;
import edu.guet.server.utils.ResultAPI;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @GetMapping("/login")
    public ResultAPI userLogin(User user) {
        log.info("登录传进的user：{}",user);
        return userService.login(user);
    }

    @Transactional
    @PostMapping("/register")//用户注册
    public ResultAPI addNewUser(@RequestBody User user){
        log.info("注册传进的user：{}",user);
        user.setImg_url("https://re.bluepoch.com/home/img/character/5c.png");
        return userService.register(user);
    }

//    @PostMapping("/test")
//    public Map<String,Object> test(String token){
//        log.info("当前token为：[{}]",token);
//        Map<String,Object> map = new HashMap<>();
//        try {
//            // 验证令牌
//            DecodedJWT verify = JWTUtils.verify(token);
//            map.put("state",true);
//            map.put("msg","请求成功");
//            return map;
//        } catch (SignatureVerificationException e) {
//            e.printStackTrace();
//            map.put("msg","无效签名！");
//        }catch (TokenExpiredException e){
//            e.printStackTrace();
//            map.put("msg","token过期");
//        }catch (AlgorithmMismatchException e){
//            e.printStackTrace();
//            map.put("msg","算法不一致");
//        }catch (Exception e){
//            e.printStackTrace();
//            map.put("msg","token无效！");
//        }
//        map.put("state",false);
//        return map;
//    }

    @PostMapping("/test")
    public ResultAPI test(User user){
        return userService.getUsername(user.getToken());
    }

}
